package ai.taromed.vr

import ai.taromed.vr.widgets.ManualHandleView
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.ImageButton
import androidx.fragment.app.Fragment
import com.google.vr.cardboard.UiLayer
import com.google.vr.sdk.widgets.common.TouchTracker
import com.google.vr.sdk.widgets.common.VrWidgetRenderer
import com.google.vr.sdk.widgets.video.VrVideoEventListener
import com.google.vr.sdk.widgets.video.VrVideoView
import java.lang.Boolean
import java.lang.reflect.Field


class PlayerFragment : Fragment() {
    companion object{
        const val TAG = "MainActivity"
        const val CONFIG_BUNDLE = "fragment_configBundle"
    }


    private var vrVideoView: VrVideoView? = null
    private var mh_scroll: ManualHandleView? = null
    private var configBundle: ConfigBundle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
        activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        activity?.window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)

    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_player , container , false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        vrVideoView = view.findViewById(R.id.vr_video_view)
        mh_scroll = view.findViewById(R.id.mh_scroll)
        vrVideoView?.setInfoButtonEnabled(false)
        vrVideoView?.setEventListener(object : VrVideoEventListener() {
            override fun onLoadSuccess() {
                super.onLoadSuccess()
                vrVideoView?.playVideo()
                disableSetting()
                enableTrackingAndVerticalTracking()
            }

            override fun onDisplayModeChanged(newDisplayMode: Int) {
                super.onDisplayModeChanged(newDisplayMode)
                disableSetting()
                enableTrackingAndVerticalTracking()
            }
        })

        configBundle = arguments!!.getSerializable(CONFIG_BUNDLE) as ConfigBundle?
        if (configBundle == null) {
            activity!!.finish()
            throw RuntimeException("config can't be null")
        }


        mh_scroll?.setListener(object: ManualHandleView.OnManualScrollListener{
            override fun onManualScroll(dx: Float, dy: Float) {
                Log.e(TAG, "-----dx:$dx, -----dy:$dy")
                rotateVideoByManual(dx , dy)
            }
        })

        // 设置全景视频路径
        val videoUri: Uri = Uri.parse(configBundle!!.filePath)
        vrVideoView?.displayMode = 3
        disableSetting()
        enableTrackingAndVerticalTracking()
        vrVideoView?.loadVideo(videoUri , null)

    }

    // 隐藏setting按钮
    private fun disableSetting(){
        vrVideoView?.let {
            var vrUiLayer:Field =  it.javaClass.superclass.getDeclaredField("vrUiLayer")
            vrUiLayer.isAccessible = true  // 设置为可访问
            val fieldValue: Any = vrUiLayer.get(it)
            if(fieldValue is UiLayer){
                var settingsButtonField =  fieldValue.javaClass.getDeclaredField("settingsButton")
                settingsButtonField.isAccessible = true  // 设置为可访问
                val settingsButton: Any = settingsButtonField.get(fieldValue)
                if(settingsButton is ImageButton){
                    settingsButton.visibility = View.GONE
                }
            }
        }
    }


    private fun rotateVideoByManual(deltaPixelX:Float , deltaPixelY:Float){
        vrVideoView?.let{
            var rendererField =  it.javaClass.superclass.getDeclaredField("renderer")
            rendererField.isAccessible = true  // 设置为可访问
            val renderer: Any = rendererField.get(it)
            if(renderer is VrWidgetRenderer){
                renderer.onPanningEvent(deltaPixelX , deltaPixelY)
            }
        }
    }

    private fun enableTrackingAndVerticalTracking(){
        vrVideoView?.let{
            var touchTrackerField =  it.javaClass.superclass.getDeclaredField("touchTracker")
            touchTrackerField.isAccessible = true  // 设置为可访问
            val touchTracker: Any = touchTrackerField.get(it)
            if(touchTracker is TouchTracker){
                Log.e(TAG , "------1111111111---------")
                var setVerticalTrackingEnabledMethod =  touchTracker.javaClass.getDeclaredMethod("setVerticalTrackingEnabled" , java.lang.Boolean.TYPE)
                setVerticalTrackingEnabledMethod.isAccessible = true  // 设置为可访问
                setVerticalTrackingEnabledMethod.invoke(touchTracker,true)
                Log.e(TAG , "------2222222222---------")
                var setTouchTrackingEnabledMethod = touchTracker.javaClass.getDeclaredMethod("setVerticalTrackingEnabled" , java.lang.Boolean.TYPE)
                setTouchTrackingEnabledMethod.isAccessible = true  // 设置为可访问
                setTouchTrackingEnabledMethod.invoke(touchTracker,true)
            }
        }
    }


    override fun onPause() {
        super.onPause()
        vrVideoView!!.pauseRendering()
    }

    override fun onResume() {
        super.onResume()
        vrVideoView!!.resumeRendering()
    }

    override fun onDestroy() {
        super.onDestroy()
        vrVideoView!!.shutdown()
    }


    fun rotateByGameHandle(dx:Float,dy:Float){
        rotateVideoByManual(dx , dy)
        activity?.runOnUiThread {
            mh_scroll?.reverse(dx , dy)
        }
    }

    fun resetManunalHandle(){
        activity?.runOnUiThread {
            mh_scroll?.onUp()
        }
    }


}